using Domain;
using MediatR;
using SqlSugar;
using System;
using System.Threading;
using System.Threading.Tasks;
using WriteAPI.Command.采购;

namespace WriteAPI.CommandHandle.采购
{
    public class DeleteCgddCommandHandler : IRequestHandler<DeleteCgddCommand, bool>
    {
        private readonly ISqlSugarClient _db;

        public DeleteCgddCommandHandler(ISqlSugarClient db)
        {
            _db = db;
        }

        public async Task<bool> Handle(DeleteCgddCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 开启事务
                bool result = false;
                
                // 使用事务
                _db.Ado.BeginTran();
                
                try
                {
                    // 查询采购订单是否存在
                    var cgdd = await _db.Queryable<Lwp_Cgdd>().FirstAsync(x => x.Id == request.Id);
                    if (cgdd == null)
                    {
                        throw new Exception($"采购订单不存在，ID: {request.Id}");
                    }

                    // 删除采购订单明细项
                    await _db.Deleteable<Lwp_CgddItem>().Where(x => x.OrderId == request.Id).ExecuteCommandAsync();

                    // 删除采购订单主体
                    await _db.Deleteable<Lwp_Cgdd>().Where(x => x.Id == request.Id).ExecuteCommandAsync();

                    // 提交事务
                    _db.Ado.CommitTran();
                    result = true;
                }
                catch (Exception ex)
                {
                    // 回滚事务
                    _db.Ado.RollbackTran();
                    throw;
                }

                return result;
            }
            catch (Exception ex)
            {
                throw new Exception($"删除采购订单失败: {ex.Message}");
            }
        }
    }
} 